package com.bdsy.api.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.bdsy.api.annotation.IgnoreAuth;
import com.bdsy.api.entity.Token;
import com.bdsy.api.service.TokenService;


@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
	
    @Autowired
    private TokenService tokenService;

    public static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	
    	System.out.println("----------------进入了检测token方法----------------");
        IgnoreAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else{
            return true;
        }

      /*  //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }*/
        
        //如果有@IgnoreAuth注解，则验证token
        if(annotation == null){
            return true;
        }

        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        if(StringUtils.isBlank(token)){
        	JSONObject jsonObject = new JSONObject();
        	jsonObject.put("code", "201");
        	jsonObject.put("msg", "token不能为空.");
        	output(jsonObject.toJSONString(), response);
        	return false;
        }

        Token userToken = tokenService.getToken(token);
        if(userToken == null || userToken.getExpireTime().getTime() < System.currentTimeMillis()){
        	
        	JSONObject jsonObject = new JSONObject();
        	jsonObject.put("code", "201");
        	jsonObject.put("msg", "token失效，请重新登录");
        	output(jsonObject.toJSONString(), response);
        	return false;
        }

        request.setAttribute(LOGIN_USER_KEY, userToken.getUserId());

        return true;
    }
    
    public void output(String jsonStr,HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8;");
		PrintWriter out = response.getWriter();
		out.write(jsonStr);
		out.flush();
		out.close();
		
	}
}
